/**
 * Copyright 2012 Woergi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gcmsms;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.gcmsms.db.Datastore;

/**
 * Servlet implementation class Login
 */
@WebServlet(name = "Login", urlPatterns = { "/Login" })
public class Login extends BaseServlet {
	private static final long serialVersionUID = 1L;

	public static final String LOGIN_ATTRIBUTE = "logon.isDone";
	public static final String LOGIN_TIME = "logon.time";
	public static final String LOGIN_TARGET = "logon.page";

	// private static final long EXPIRE_TIME = 60000; // ms -> 1min

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse response)
			throws IOException, ServletException {

		/*
		 * if someone is logged in, then log out before prompting the login
		 * dialog
		 */
		logout(req.getSession());

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		out.print("<html><body>");
		out.print("<head>");
		out.print("  <title>GCMSms Login</title>");
		out.print("<link href='login.css' rel='stylesheet' type='text/css'/>");
		out.print("</head>");

		out.print("<div id='table'>");
		out.print("<div id='cell'>");
		out.print("<div class='modal-dialog'>");
		out.print("<h2>Authenticate</h2>");
		out.print("<form name='form' method='POST' action='Login'>");
		out.print("<input type='text' name='user' value='Username' /><br />");
		out.print("<input type='password' name='pass' value='*********' /><br />");
		out.print("<input type='submit' value='Log In' />");
		out.print("</form>");
		out.print("</div></div></div>");

		out.print("</body></html>");
		response.setStatus(HttpServletResponse.SC_OK);

		req.getSession().setAttribute(LOGIN_TARGET, "Home");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();

		String username = getParameter(req, "user", "nobody");
		String password = getParameter(req, "pass", "nobody");
		if (Datastore.getInstance().authenticateCredentials(username, password) == false) {
			if (DEBUG) {
				out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>");
				out.println("<BODY>Your login and password are invalid.<BR>");
				out.println("You may want to <A HREF=''>try again</A>");
				out.println("</BODY></HTML>");
			} else {
				doGet(req, res);
			}
		} else {
			// Valid login. Make a note in the session object.
			HttpSession session = req.getSession();
			session.setAttribute(LOGIN_ATTRIBUTE, username);
			session.setAttribute(LOGIN_TIME, System.currentTimeMillis());
			// Try redirecting the client to the page he first tried to access
			try {
				res.sendRedirect(HomeServlet.class.getAnnotation(
						WebServlet.class).name());
				return;
			} catch (Exception ignored) {
			}

			// Couldn't redirect to the target. Redirect to the site's home
			// page.
			res.sendRedirect("/");
		}
	}

	private boolean checkLoggedIn(HttpSession session) {
		Object loginAtr = session.getAttribute(LOGIN_ATTRIBUTE);

		if (loginAtr != null)
			return true;

		return false;
	}

	private void logout(HttpSession session) {
		if (checkLoggedIn(session)) {
			session.removeAttribute(LOGIN_ATTRIBUTE);
			session.removeAttribute(LOGIN_TIME);
			session.removeAttribute(LOGIN_TARGET);
		}
	}

	// private void forwardIfLoggedIn(HttpServletRequest req,
	// HttpServletResponse response) throws ServletException, IOException {
	// HttpSession session = req.getSession();
	// Long logonTime = (Long) session.getAttribute(LOGIN_TIME);
	// if (session.getAttribute(LOGIN_ATTRIBUTE) != null && logonTime != null
	// && (logonTime + EXPIRE_TIME) > System.currentTimeMillis()) {
	// getServletContext().getRequestDispatcher("/Home").forward(req,
	// response);
	// } else {
	// session.removeAttribute(LOGIN_ATTRIBUTE);
	// session.removeAttribute(LOGIN_TIME);
	// }
	// }
}
